import Vue from 'vue'
import Vuex from 'vuex'
import {getUserInfo,getUserAddress} from '@/api/mine'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo:[],
    userAddress:[{"address":"请设置地址"}],
    order:[],
    chatHistory:[],
    chatUserList:[]
  },
  mutations: {
    SET_USER_INFO:(state,data)=>{
      state.userInfo=data
    },
    SET_USER_ADDRESS:(state,data)=>{
      state.userAddress=data
    },
    SET_ORDER:(state,data)=>{
      state.order=data
    },
    UPDATE_CHAT_HISTORY:(state,data)=>{
      state.chatUserList.forEach(item=>{
        if(item.userID.toString()===data.sender||item.userID.toString()===data.receiver){
          item.historyList.push(data)
        }
      })
    },
    SET_CHAT_USER:(state,data)=>{
      let isrepeat=false
      for(let key in state.chatUserList){
        if(state.chatUserList[key].userID===data.userID){
          isrepeat=true
        }
      }
      if(isrepeat===false){
        state.chatUserList.push(data)
      }
    }
  },
  actions: {
    getUserInfo ({commit}, params) {
      return new Promise((resolve, reject) => {
        getUserInfo(params).then(response => {
          const { data } = response
          if(localStorage.getItem("certified")==="false"&&data.certified==="true") localStorage.setItem("certified","true")
          commit('SET_USER_INFO', data)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserAddress({commit}, params) {
      console.log(params)
      return new Promise((resolve, reject) => {
        getUserAddress(params).then(response => {
          const { data } = response
          if(data){
            commit('SET_USER_ADDRESS', data)
          }
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },
  },

})
